from app import create_app
from models import db, HierarchyConfig, RequirementType, RequirementClassification, RequirementPool, Communication, Diagram
from datetime import datetime, timedelta

app = create_app()

def calculate_priority(business_value, urgency, complexity):
    """计算综合优先级 (避免导入循环)"""
    return max(1, min(10, (business_value * 5 + urgency * 3 - complexity * 2) // 3))

def initialize_database():
    with app.app_context():
        # 创建所有表
        db.create_all()
        print("数据库表创建完成")
        
        # 添加初始业务层级
        if not HierarchyConfig.query.first():
            print("添加初始业务层级...")
            # L1 业务域
            scm_domain = HierarchyConfig(
                node_id="DOM-SCM",
                level="L1",
                code="SCM",
                name="供应链",
                version="v1.0"
            )
            
            fin_domain = HierarchyConfig(
                node_id="DOM-FIN",
                level="L1",
                code="FIN",
                name="财务",
                version="v1.0"
            )
            
            # L2 业务能力
            warehouse_cap = HierarchyConfig(
                node_id="CAP-WH",
                level="L2",
                code="WH",
                name="仓储管理",
                parent_id="DOM-SCM",
                version="v1.0"
            )
            
            cost_cap = HierarchyConfig(
                node_id="CAP-COST",
                level="L2",
                code="COST",
                name="成本控制",
                parent_id="DOM-FIN",
                version="v1.0"
            )
            
            # L3 核心流程
            inbound_proc = HierarchyConfig(
                node_id="PROC-IN",
                level="L3",
                code="IN",
                name="入库流程",
                parent_id="CAP-WH",
                version="v1.0"
            )
            
            outbound_proc = HierarchyConfig(
                node_id="PROC-OUT",
                level="L3",
                code="OUT",
                name="出库流程",
                parent_id="CAP-WH",
                version="v1.0"
            )
            
            db.session.add_all([scm_domain, fin_domain, warehouse_cap, cost_cap, inbound_proc, outbound_proc])
        
        # 添加初始需求类型
        if not RequirementType.query.first():
            print("添加初始需求类型...")
            types = [
                RequirementType(
                    type_id="FIN-ADAPT",
                    name="财务适应性需求",
                    itil_category="适应性",
                    allowed_levels="L3,L4,L5",
                    domain_code="FIN"
                ),
                RequirementType(
                    type_id="SCM-PREV",
                    name="供应链预防性需求",
                    itil_category="预防性",
                    allowed_levels="L1,L2",
                    domain_code="SCM"
                ),
                RequirementType(
                    type_id="SCM-CORR",
                    name="供应链纠正性需求",
                    itil_category="纠正性",
                    allowed_levels="L3,L4,L5",
                    domain_code="SCM"
                )
            ]
            db.session.add_all(types)
        
        # 添加示例需求
        if not RequirementClassification.query.first():
            print("添加示例需求...")
            # 创建分类
            classification = RequirementClassification(
                req_id="REQ-IN-ADAPT-20250702-001",
                node_id="PROC-IN",
                type_id="FIN-ADAPT",
                full_path="供应链 > 仓储管理 > 入库流程",
                value_metric="质检时间减少30%",
                impact_dimensions="组织与人员,技术系统"
            )
            
            # 创建需求池条目
            pool = RequirementPool(
                req_id="REQ-IN-ADAPT-20250702-001",
                request_time=datetime.utcnow() - timedelta(days=5),
                expected_solve_time=datetime.utcnow() + timedelta(days=30),
                business_value=4,
                complexity=3,
                urgency=4,
                priority=calculate_priority(4, 4, 3),  # 使用本地函数计算
                status="开发",
                description="优化入库质检流程，减少人工操作时间",
                solution="开发自动化质检模块",
                solution_owner="张工程师",
                type_code="FIN-ADAPT",
                status_update_time=datetime.utcnow() - timedelta(days=2)
            )
            
            db.session.add(classification)
            db.session.add(pool)
        if not Communication.query.first():
            print("添加示例沟通纪要...")
            meeting_time = datetime.utcnow() - timedelta(days=3)
            
            comm1 = Communication(
                comm_id="MTG-20250702-001",
                meeting_time=meeting_time,
                location="会议室A",
                department="供应链管理部",
                recorder="张经理",
                proposer="王总监",
                method="会议",
                content="讨论入库流程优化方案，重点解决质检环节效率问题",
                notes="需在两周内提供详细方案",
                related_req_id="REQ-IN-ADAPT-20250702-001",
                l3_value_stream="PROC-IN",
                action_items="李工@调研自动化质检方案@2025-07-10\n张工@制定实施方案@2025-07-15"
            )
            
            comm2 = Communication(
                comm_id="MTG-20250703-001",
                meeting_time=datetime.utcnow() - timedelta(days=1),
                location="线上会议",
                department="财务部",
                recorder="赵会计",
                proposer="钱经理",
                method="视频会议",
                content="讨论成本控制模块的新需求",
                notes="需要与IT部门进一步确认技术可行性",
                action_items="孙工@准备需求文档@2025-07-08"
            )
            
            db.session.add_all([comm1, comm2])
            db.session.commit()
            print("已创建示例沟通纪要")
        
        try:
            db.session.commit()
            print("数据库初始化完成！已创建示例数据")
        except Exception as e:
            db.session.rollback()
            print(f"数据库提交失败: {str(e)}")
            import traceback
            traceback.print_exc()
        
        # 添加示例图表
        if not Diagram.query.first():
            print("添加示例图表...")
            diagram1 = Diagram(
                req_id="REQ-IN-ADAPT-20250702-001",
                diagram_type="erd",
                title="入库流程实体关系图",
                mermaid_code="""erDiagram
    WAREHOUSE ||--o{ STORAGE_AREA : contains
    STORAGE_AREA ||--|{ LOCATION : has
    PRODUCT ||--o{ INVENTORY : has
    INVENTORY }|--|| LOCATION : stored_in
    SUPPLIER ||--o{ PURCHASE_ORDER : provides
    PURCHASE_ORDER ||--|{ RECEIVING : generates
    RECEIVING ||--|{ INVENTORY : creates"""
            )
            
            diagram2 = Diagram(
                req_id="REQ-IN-ADAPT-20250702-001",
                diagram_type="sequence",
                title="质检环节时序图",
                mermaid_code="""sequenceDiagram
    participant W as 仓库管理员
    participant S as 质检系统
    participant D as 数据库
    
    W->>S: 提交质检请求
    S->>D: 查询产品标准
    D-->>S: 返回标准数据
    S->>W: 显示质检表单
    W->>S: 填写质检结果
    S->>D: 更新库存状态
    D-->>S: 操作成功
    S-->>W: 显示完成通知"""
            )
            
            db.session.add_all([diagram1, diagram2])
            db.session.commit()

if __name__ == '__main__':
    initialize_database()